import 'package:flutter/material.dart';
import 'package:gd_assistant/api/apiHandler.dart';
import 'package:gd_assistant/model/extensionModel.dart';
import 'package:gd_assistant/page/public/colors.dart';
import 'package:gd_assistant/page/public/publicItem.dart';
import 'package:gd_assistant/page/public/publicView.dart';
import 'package:gd_assistant/page/public/themeUtils.dart';
import 'package:gd_assistant/third/flutter_datetime_picker.dart';
import 'package:gd_assistant/util/RelativeDateFormat.dart';
import 'package:gd_assistant/util/customRoute.dart';
import 'package:gd_assistant/util/eventBus.dart';


class appointmentTimePage extends StatefulWidget {
  appointmentTimePage({Key key, 
                      this.packageOrderId}) : super(key : key);
  String packageOrderId = '';
  @override
  _appointmentTimeState createState() => _appointmentTimeState();
}

class _appointmentTimeState extends State<appointmentTimePage> {
  bool isDark = false;
  List<AppointmentTime> data = [];
  @override
  void initState() {
    super.initState();
    loadData();
  }
  
  loadData() async {
    data = await apiHandler.getPackageAppointmentList(widget.packageOrderId);
    setState(() {});
  }

  Widget header() {
    return GestureDetector(
      onTap: (){
        Navigator.of(context).push(CustomRoute(customAppointmentTimePage()));
      },
      child: Container(
        margin: EdgeInsets.only(bottom: 5),
        padding: EdgeInsets.only(top: 15,bottom: 15),
        color: isDark ? Colours.dark_bg_gray : Colors.white,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Icon(Icons.add_circle,color: Colors.blue),
            Text("自定义时间地点",style: TextStyle(fontSize: 18,fontWeight: FontWeight.w500))
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    isDark = ThemeUtils.isDark(context);
    return Scaffold(
      backgroundColor: isDark ? Colours.dark_bg_gray : Colours.bg_color,
      appBar: AppBar(
        title: Text("预约"),
        elevation: 0
      ),
      body: Container(
        child: Column(
          children: <Widget>[
            Expanded(
              flex: 1,
              child: ListView.builder(itemBuilder: (context, index){
                if (index == 0) {
                  return header();
                }
                return appointmentTimeItem(
                  appointment: data[index-1],
                  onTap: (){
                    Navigator.of(context).push(
                      CustomRoute(appointTimeSelectPage(appointmentTime: data[index-1], packageOrderId: widget.packageOrderId))
                    ); 
                  },
                );
              },
              itemCount: data.length + 1),
            ),
          ],
        )
      ),
    );
  }
}

//自定义预约的页面
class customAppointmentTimePage extends StatefulWidget {
  @override
  _customAppointmentTimeState createState() => _customAppointmentTimeState();
}

class _customAppointmentTimeState extends State<customAppointmentTimePage> {
  bool isDark = false;
  var appointTime = "";
  TextEditingController appointAare = TextEditingController();

  Widget header() {
    return Container(
      padding: EdgeInsets.only(top: 15,bottom: 15),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text("不占用医生现有出诊时间",style: TextStyle(fontSize: 16,fontWeight: FontWeight.w500,color: Colors.grey[600]))
        ],
      ),
    );
  }
  @override
  void dispose() {
    super.dispose();
    appointAare.dispose();
  }
  @override
  void initState() {
    super.initState();
    appointAare.addListener(() {setState(() {});});
  }
  @override
  Widget build(BuildContext context) {
    isDark = ThemeUtils.isDark(context);
    return Scaffold(
      appBar: AppBar(
        title: Text("预约"),
        elevation: 0
      ),
      body: Container(
        child: Column(
          children: <Widget>[
            Expanded(
              flex: 1,
              child: ListView(
                children: <Widget>[
                  header(),
                  ZLSelectField(
                    title: "预约时间",
                    text: appointTime,
                    pliceHorder: "请选择预约时间",
                    onTap: () {
                      DatePicker.showDateTimePicker(context,
                          showTitleActions: true,
                          onConfirm: (date) {
                          appointTime = date.toString().substring(0,16);
                          setState(() {});
                      }, locale: LocaleType.zh);
                    },
                  ),
                  ZLTextView(
                    title: "预约地点",
                    controller: appointAare,
                    pliceHorder: "请输入地点",
                  ),
                  Padding(
                    padding: EdgeInsets.only(top: 10),
                  ),
                  ZLButton(
                    title: "完成",
                    onTap: appointTime.length > 0 && appointAare.text.length > 0 ? (){
                      EventBus().emit("timeAndAddressChange",{
                        "address":appointAare.text,
                        "time": appointTime
                      });
                      Navigator.popUntil(context,  ModalRoute.withName('/appointmentInfo'));
                    } : null,
                  )
                ],
              ),
            ),
          ],
        )
      ),
    );
  }
}


//预约页面的选择
class appointTimeSelectPage extends StatefulWidget {
  appointTimeSelectPage({Key key, 
                      this.packageOrderId,
                      this.appointmentTime}) : super(key : key);
  AppointmentTime appointmentTime;
  String packageOrderId = '';
  @override
  _appointTimeSelectPageState createState() => _appointTimeSelectPageState();
}

class _appointTimeSelectPageState extends State<appointTimeSelectPage> {
  bool isDark = false;
  WorkTime work;
  String selectedTime = "";

  Widget gridViewDefaultCount(WorkTime work) {
    return GridView.count(
      padding: EdgeInsets.only(bottom: 10),
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      crossAxisCount: 4,
      scrollDirection: Axis.vertical,
      crossAxisSpacing: 2.0,
      mainAxisSpacing: 2.0,
      childAspectRatio: 2 / 2,
      children: initListWidget(work != null ? work.workTimes : [],work != null ? work.bookedTimes : []),
    );
  }
    
  List<Widget> initListWidget(List list, List books) {
    List<Widget> lists = [];
    for (String item in list) {
      bool isApp = false;
      for (String book in books) {
        if (book == item) {
          isApp = true;
        }
      }
      lists.add(GestureDetector(
        onTap: (){
          if (!isApp) {
            selectedTime = item;
            setState(() {});
          }
        },
        child: new Container(
          height: 50.0,
          width: 50.0,
          color: isApp ? Colors.grey[200] : item == selectedTime ? Colors.blue : isDark ? Colours.dark_bg_gray : Colors.white,
          child: new Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(item,style: TextStyle(color: item == selectedTime ? Colors.white : isDark ? Colors.white : Colors.black)),
                  Offstage(
                    offstage: !isApp,
                    child: Text("(已约)",style: TextStyle(color: Colors.grey)),
                  )
                ],
              )
            ),
        ),
      ));
    }
    return lists;
  }
  
  @override
  void initState() {
    super.initState();
    loadData();
  }

  loadData() async {
    work = await apiHandler.getPackageAppointmentTime(widget.packageOrderId, widget.appointmentTime.visitPlanDate,  widget.appointmentTime.visitPlanPeriod);
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    final EdgeInsets padding = MediaQuery.of(context).padding;
    isDark = ThemeUtils.isDark(context);
    return Scaffold(
      backgroundColor: isDark ? Colours.dark_bg_gray : Colours.bg_color,
      appBar: AppBar(
        title: Text("预约"),
        elevation: 0,
      ),
      body: Container(
        child: Column(
          children: <Widget>[
            Expanded(
              flex: 1,
              child: ListView(
                children: <Widget>[
                  gridViewDefaultCount(work),
                  appointmentTimeItem(
                    appointment: widget.appointmentTime,
                  )
                ],
              ),
            ),
           Container(
              padding: EdgeInsets.only(bottom: padding.bottom),
              width: double.infinity,
              height: 65 + padding.bottom,
              color: isDark ? Colours.dark_bg_gray : Colors.white,
              child: ZLButton(
                title: "确认",
                onTap: selectedTime.length > 0 ? (){
                  EventBus().emit("timeAndAddressChange",{
                    "address":widget.appointmentTime.visitPlanPlace,
                    "time":RelativeDateFormat.YMDformat(widget.appointmentTime.visitPlanDate) + " " +selectedTime
                  });
                  Navigator.popUntil(context,  ModalRoute.withName('/appointmentInfo'));
                } : null,
              )
            ),
          ],
        )
      ),
    );
  }
}